<?php

/**
 * 缩略图处理类 Thumb.class.php
 * Author: 勾国印 (gouguoyin@ethank.com.cn) 
 * Date: 2015年7月25日 下午4:21:40  
*/

namespace Common\Lib;
class Thumb{
    public $attachment_id; // 允许上传图片的最大大小
    public $width = null; // 允许上传文件的最大大小
    public $height = null; // 允许上传的图片后缀

    //初始化参数
    public function __construct($attachment_id, $width = null, $height = null) {
        $this->attachment_id  = $attachment_id; 
        $this->width  = $width;
        $this->height  = $height;
        
        $this->creat($this->attachment_id, $this->width, $this->height);
    }
    
    function creat($attachment_id, $width = null, $height = null, $filename = null)
    {
        if(is_numeric($attachment_id)){
            $attachment_info = uri('attachment', $attachment_id);
    
            $src = ROOT_PATH.'/uploads'.$attachment_info['path'].$attachment_info['save_name'].'.'.$attachment_info['suffix'];
    
        }else if(is_string($attachment_id)){
            $src = $attachment_id;
        }else{
            return IMAGE_PATH.'/default.jpg';
        }
    
        if (!isset($width) && !isset($height))
            return false;
        if (isset($width) && $width <= 0)
            return false;
        if (isset($height) && $height <= 0)
            return false;
    
        $size = getimagesize($src);
        if (!$size)
            return false;
    
        list($src_w, $src_h, $src_type) = $size;
        $src_mime = $size['mime'];
        switch($src_type) {
            case 1 :
                $img_type = 'gif';
                break;
            case 2 :
                $img_type = 'jpeg';
                break;
            case 3 :
                $img_type = 'png';
                break;
            case 15 :
                $img_type = 'wbmp';
                break;
            default :
                return false;
        }
    
        if (!isset($width))
            $width = $src_w * ($height / $src_h);
        if (!isset($height))
            $height = $src_h * ($width / $src_w);
    
        $imagecreatefunc = 'imagecreatefrom' . $img_type;
        $src_img = $imagecreatefunc($src);
        $dest_img = imagecreatetruecolor($width, $height);
        imagecopyresampled($dest_img, $src_img, 0, 0, 0, 0, $width, $height, $src_w, $src_h);
    
        $imagefunc = 'image' . $img_type;
        if ($filename) {
            $imagefunc($dest_img, $filename);
        } else {
            header('Content-Type: ' . $src_mime);
            $imagefunc($dest_img);
        }
        imagedestroy($src_img);
        imagedestroy($dest_img);
    
        return true;
    }

 

}